
import { defineStore } from 'pinia'

// 定义存储
export const useMainStore = defineStore('main', {
    // 状态定义
    state: () => ({
      token: null,
      links: [],
      categories: [],
      lastModified: -1,
      config: {
        enableNoAuth: false,
        enableNoAuthView: false,
      },
    }),
  
    // 操作方法
    actions: {
      // 设置令牌
      setToken(token) {
        console.log('设置令牌:', token);
        this.token = token;
      },
      
      // 获取配置
      async fetchConfig() {
        try {
          this.config = await api.getConfig();
        } catch (error) {
          console.error('获取配置失败:', error);
        }
        return this.config;
      },
      
      // 登出
      logout() {
        this.token = null;
        this.links = [];
        this.categories = [];
        this.lastModified = -1;
      },
      
      // 验证令牌是否有效
      async validateToken() {
        if (!this.token) return false;
  
        try {
          await api.validateToken();
          return true;
        } catch (error) {
          // 如果token无效，清除存储的token
          this.logout();
          return false;
        }
      },
      
      // 获取导航数据
      async getNavigation() {
        const lastModifiedResponse = await api.getLastModified();
        if (this.lastModified === lastModifiedResponse.lastModified) {
          return {
            links: this.links,
            categories: this.categories,
          };
        }
        
        const { links, categories, lastModified } = await api.getNavigation();
        this.links = links;
        this.categories = categories;
        this.lastModified = lastModified;
        return { links, categories };
      },
    },
  
    // 启用持久化
    persist: true
  });